package com.roc.web.action.settlemorg;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.bean.AccountBalance;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.TblInsInf;
import com.roc.service.IAccountBalanceService;
import com.roc.service.IPagenitionService;
import com.roc.service.ServiceException;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;

@Component
@Scope("prototype")
@Namespace("/accountBalance")
public class AccountBalanceAction extends PaginationBaseAction{
	
	
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1685486845102690069L;
	private AccountBalanceActionSearchCondition searchCondition;
	private static Logger logger = LogManager.getLogger(SettlementOrgMoneyAction.class);
	private AccountBalance accountBalance;
	private String acctBalKey;
	private List<AccountBalance> acctBalList=new ArrayList<AccountBalance>();
	private List<TblInsInf> orgList=new ArrayList<TblInsInf>();
	@Autowired
	private IAccountBalanceService service;
	@Autowired
	private IPagenitionService pagenitionService;
	
	/**
	 * 初始余额查询页面
	 * @return
	 */
	@Action(value="init",results={@Result(name="success",location="/pages/settlementOrg/acctlist.jsp"),
			@Result(name = "error", location = "/error.jsp")})
	public String queryMakeMoneyJsp(){
		try {
			Operators op = (Operators) getSession().getAttribute(
				Constant.SESSION_LOGIN_MERCHANT);
			if (op.getRoleType().equals(Role.CLEAR_OPERATORS.getCode())
				|| op.getRoleType().equals(Role.CLEAR_LEAD.getCode())
				|| op.getRoleType().equals(Role.SYSTEM.getCode())) {
				searchCondition=new AccountBalanceActionSearchCondition();
				List<TblInsInf> queryOrgList= service.loadOrgCode();
				if(queryOrgList!=null){
					orgList.addAll(queryOrgList);
				}
				return SUCCESS;
			}
			addActionError("无权限访问!!!");
		} catch (ServiceException e) {
			logger.error(e.getMessage(),e);
			addActionError("余额初始化失败");
		}
		return ERROR;
	}
	
	/**
	 *余额查询
	 * @return
	 */
	@Action(value="queryAcctBalance",results={@Result(name="success",location="/pages/settlementOrg/acctlist.jsp"),
			@Result(name = "error", location = "/error.jsp")})
	public String querySettlementMsgList(){
		try {
			Operators op = (Operators) getSession().getAttribute(
					Constant.SESSION_LOGIN_MERCHANT);
			if (op.getRoleType().equals(Role.CLEAR_OPERATORS.getCode())
					|| op.getRoleType().equals(Role.CLEAR_LEAD.getCode())
					|| op.getRoleType().equals(Role.SYSTEM.getCode())) {
				if(searchCondition == null){
					searchCondition = (AccountBalanceActionSearchCondition) getSearchConditionFromSession();
					if(searchCondition == null){
						searchCondition = new AccountBalanceActionSearchCondition();
					}
				}
				
				int rows=pagenitionService.countSQL(searchCondition);
				if(rows>0){
					searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
				}
				List<TblInsInf> queryOrgList= service.loadOrgCode();
				if(queryOrgList!=null){
					orgList.addAll(queryOrgList);
				}
				dealWithTheListSpecially(searchRsList);
				this.setTotalPage(this.calcuTotalPage(rows));
				getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
				getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
				setSearchToConditionSession(searchCondition);
				return SUCCESS;
			}
			addActionError("无权限访问!!!");
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			addActionError("余额查询异常");
			return ERROR;
		}
		return ERROR;
	}
	/**
	 * 初始化添加页面
	 * @return
	 */
	@Action(value="addAcctBalanceinit",results={@Result(name="success",location="/pages/settlementOrg/addAcctBal.jsp"),
			@Result(name = "error", location = "/error.jsp")			
	})
	public String addAcctBalanceinit(){
		try {
			Operators op = (Operators) getSession().getAttribute(
					Constant.SESSION_LOGIN_MERCHANT);
			if (op.getRoleType().equals(Role.CLEAR_OPERATORS.getCode())
					|| op.getRoleType().equals(Role.CLEAR_LEAD.getCode())
					|| op.getRoleType().equals(Role.SYSTEM.getCode())) {
				List<TblInsInf> queryOrgList= service.loadOrgCode();
				if(queryOrgList!=null){
					orgList.addAll(queryOrgList);
				}
				if(orgList.size()==0){
					TblInsInf ins=new TblInsInf();
					ins.setInsIdCd("");
					ins.setInsName("请选择");
					orgList.add(ins);
				}
				return SUCCESS;
			}
			addActionMessage("无权限访问!");
		} catch (ServiceException e) {
			logger.error(e.getMessage(),e);
			addActionError("添加余额初始化失败");
		}
		return ERROR;
	}
	/**
	 * 初始化修改页面
	 * @return
	 */
	@Action(value="updateAcctBalanceinit",results={@Result(name="success",location="/pages/settlementOrg/addAcctBal.jsp"),
			@Result(name = "error", location = "/error.jsp")			
	})
	public String updateAcctBalanceinit(){
		try {
			Operators op = (Operators) getSession().getAttribute(
					Constant.SESSION_LOGIN_MERCHANT);
			if (op.getRoleType().equals(Role.CLEAR_OPERATORS.getCode())
					|| op.getRoleType().equals(Role.CLEAR_LEAD.getCode())
					|| op.getRoleType().equals(Role.SYSTEM.getCode())) {
				getRequest().setAttribute("target","update");//设置标记				
				String[] indexs=acctBalKey.split(",");
				AccountBalance abala=new AccountBalance();
				abala.setCurrentDate(indexs[0]);
				abala.setOrgCode(indexs[1]);
				abala.setAccount(indexs[2]);
				accountBalance=service.queryAccountBalance(abala);
				if(accountBalance!=null){
					List<TblInsInf> org = service.loadOrgCode();
					if(org!=null){
						for(TblInsInf tbl:org){
							if(tbl.getInsIdCd().equals(accountBalance.getOrgCode())){
								orgList.add(tbl);
								break;
							}
						}
					}
					
					if(orgList.size()==0){
						TblInsInf gen=new TblInsInf();
						gen.setInsIdCd(accountBalance.getOrgCode());
						gen.setInsName("未知机构");
						orgList.add(gen);
					}
					return SUCCESS; 
				}else{
					addActionError("当前数据不匹配");
				}
				
			}
			addActionMessage("无权限访问!");
		} catch (ServiceException e) {
			logger.error(e.getMessage(),e);
			addActionError("修改余额初始化失败");
		}
		return ERROR;
	}
	@Action(value="addAcctBalance",results={@Result(name="success",location="/pages/settlementOrg/acctlist.jsp"),
			@Result(name = "failed", location = "/pages/settlementOrg/addAcctBal.jsp"),
			@Result(name = "error", location = "/error.jsp")			
	})
	public String addAcctBalance(){
		try {
				Operators op = (Operators) getSession().getAttribute(
						Constant.SESSION_LOGIN_MERCHANT);
				if (op.getRoleType().equals(Role.CLEAR_OPERATORS.getCode())
						|| op.getRoleType().equals(Role.CLEAR_LEAD.getCode())
						|| op.getRoleType().equals(Role.SYSTEM.getCode())) {
						List<TblInsInf> queryOrgList= service.loadOrgCode();
						if(queryOrgList!=null){
							orgList.addAll(queryOrgList);
						}
						Map<String,String> map=service.insertAccountBalanceData(accountBalance, op);
						String result=map.get("result");
						addActionMessage(result);
						logger.info(result);
						if(map.containsKey("flag")){
							return SUCCESS;
						}
						if(orgList.size()==0){
							TblInsInf ins=new TblInsInf();
							ins.setInsIdCd("");
							ins.setInsName("请选择");
							orgList.add(ins);
						}
						return "failed";		
				}
				addActionMessage("无权限访问!");
			} catch (ServiceException e) {
				logger.error(e.getMessage(),e);
				addActionError("余额添加异常");
				return ERROR;
			}			
		return ERROR;
	}
	@Action(value="updateAcctBalance",results={@Result(name="success",location="/pages/settlementOrg/acctlist.jsp"),
			@Result(name = "failed", location = "/pages/settlementOrg/addAcctBal.jsp"),
			@Result(name = "error", location = "/error.jsp")			
	})
	public String updateAcctBalance(){
		try {
				Operators op = (Operators) getSession().getAttribute(
						Constant.SESSION_LOGIN_MERCHANT);
				if (op.getRoleType().equals(Role.CLEAR_OPERATORS.getCode())
						|| op.getRoleType().equals(Role.CLEAR_LEAD.getCode())
						|| op.getRoleType().equals(Role.SYSTEM.getCode())) {
					List<TblInsInf> queryOrgList= service.loadOrgCode();	
					Map<String,String> map=service.updateAccountBalanceData(accountBalance, op);
						String result=map.get("result");
						addActionMessage(result);
						logger.info(result);
						if(map.containsKey("flag")){
							if(queryOrgList!=null){
								orgList.addAll(queryOrgList);
							}
							return SUCCESS;
						}
						//取其一
						getRequest().setAttribute("target","update");//设置标记
						if(accountBalance!=null){
							if(queryOrgList!=null){
								for(TblInsInf tbl:queryOrgList){
									if(tbl.getInsIdCd().equals(accountBalance.getOrgCode())){
										orgList.add(tbl);
										break;
									}
								}
							}
							
							if(orgList.size()==0){
								TblInsInf gen=new TblInsInf();
								gen.setInsIdCd(accountBalance.getOrgCode());
								gen.setInsName("未知机构");
								orgList.add(gen);
							}
							return "failed"; 
						}
				}else{
					addActionMessage("无权限访问!");
				}				
			} catch (ServiceException e) {
				logger.error(e.getMessage(),e);
				addActionError("余额添加异常");
				return ERROR;
			}			
		return ERROR;
	}
	@Override
	protected void dealWithTheListSpecially(List<Object> list) {
		DecimalFormat dlf=new DecimalFormat("0.00");
		if(list!=null&&list.size()>0){
			for(int i=0;i<list.size();i++){
				Object[] obj=(Object[]) list.get(i);
				AccountBalance acctBal=new AccountBalance();
				acctBal.setCurrentDate(Constance.Null2EmptyTrim(obj[0]));
				acctBal.setOrgCode(Constance.Null2EmptyTrim(obj[1]));
				acctBal.setOrgCodeName(Constance.Null2EmptyTrim(obj[2]));
				acctBal.setAccount(Constance.Null2EmptyTrim(obj[3]));
				String amt=Constance.Null2EmptyTrim(obj[4]);
				if("".equals(amt)){
					acctBal.setAmt("0.00");
				}else{					
					acctBal.setAmt(dlf.format(Double.parseDouble(amt)));
				}				
				acctBal.setLastTransDt(Constance.Null2EmptyTrim(obj[5]));
				acctBal.setLastTransTm(Constance.Null2EmptyTrim(obj[6]));
				acctBal.setLastKeyRsp(Constance.Null2EmptyTrim(obj[7]));				
				String lastTransAMT=Constance.Null2EmptyTrim(obj[8]);
				if(!"".equals(lastTransAMT)){
					acctBal.setLastTransAMT(dlf.format(Double.parseDouble(lastTransAMT)));
				}else{
					acctBal.setLastTransAMT(lastTransAMT);
				}				
				acctBal.setStatus(Constance.Null2EmptyTrim(obj[9]));				
				acctBalList.add(acctBal);
			}
			
		}
	}

	public AccountBalanceActionSearchCondition getSearchCondition() {
		return searchCondition;
	}






	public void setSearchCondition(
			AccountBalanceActionSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}






	public AccountBalance getAccountBalance() {
		return accountBalance;
	}






	public void setAccountBalance(AccountBalance accountBalance) {
		this.accountBalance = accountBalance;
	}


	



	public List<AccountBalance> getAcctBalList() {
		return acctBalList;
	}

	public void setAcctBalList(List<AccountBalance> acctBalList) {
		this.acctBalList = acctBalList;
	}
	
	
	public List<TblInsInf> getOrgList() {
		return orgList;
	}

	public void setOrgList(List<TblInsInf> orgList) {
		this.orgList = orgList;
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_ACCOUNT_BALANCE_QUERY, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		return (AccountBalanceActionSearchCondition)getSession().getAttribute(SEARCH_SESSION_ACCOUNT_BALANCE_QUERY);
	}

	@Override
	protected String getInitPageSize() {
		return Constance.PAGE_MAX_SIZE+"";
	}

	public String getAcctBalKey() {
		return acctBalKey;
	}

	public void setAcctBalKey(String acctBalKey) {
		this.acctBalKey = acctBalKey;
	}
	
}
